import React, {Component} from 'react';
import ReactDom from 'react-dom';
import { FormattedMessage, injectIntl } from 'react-intl';
import {actions} from "mirrorx";
import {Table, Checkbox, Button, Modal, Message} from "tinper-bee";
import DatePicker from "bee-datepicker";
import cloneDeep from 'lodash.clonedeep';
import multiSelect from "bee-table/build/lib/multiSelect.js";
import RefComponent from 'components/RefComponent';
import FormList from 'components/FormList';
import {ts2Formatter} from 'utils';

let {RangePicker} = DatePicker;
const MultiSelectTable = multiSelect(Table, Checkbox)

import './index.less'

const FormItem = FormList.Item;

class CreateCustomer extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }

    }
    
    componentWillReceiveProps(nextProps){
        if(!this.state.shareList && nextProps.showCreateCustomerModal) {
            this.setState({
                shareList:nextProps.shareList
            })
        }
        
      }

    createCustomer = (delFlag) => {
        let { selectData } = this.props;
    
        if (delFlag) {
            this.props.form.validateFields((err, _values) => {
                let supplierCategoryId = _values.supplierCategoryId && JSON.parse(_values.supplierCategoryId).refpk;
                if(!supplierCategoryId) {
                    err = true;
                }
                if(err) {
                    Message.create({ content: '请输入值', color: 'warning' });
                }else {
                    let param = {
                        supplierCateId:supplierCategoryId,
                        id:selectData[0].id
                    }
                    actions.ActivityDesign.createCustomer(param);
                    this.props.closeCreateModal();
                }
                
            })

            
            
        }else {
            this.props.closeCreateModal();
        }
        

    }

    getSelectedDataFunc = (selectedList, record, index, newData) => {
        let { shareList } = this.state;
        let _list = cloneDeep(shareList);
        //当第一次没有同步数据
        // if (this.oldData.length == 0) {
        //     this.oldData = deepClone(list);
        // }
        //同步list数据状态
        if (index != undefined) {
          _list[index]['_checked'] = !_list[index]['_checked'];
        } else {//点击了全选
          if (selectedList.length > 0) {//全选
            _list.map(item => {
              if (!item['_disabled']) {
                item['_checked'] = true
              }
            });
          } else {//反选
            _list.map((item,index) => {
              if (!item['_disabled']) {
                item['_checked'] = false
              }
            });
          }
        }
        this.setState({shareList:_list,SelectIndex:index,selectedList:selectedList});
    }

    delPerson = () => {
        let {selectedList} = this.state;
        let param=[];
        let {selectData} = this.props;
        let {shareList} = this.state;
        selectedList.map((item,index)=> {
            param.push({
                "billId": selectData[0].id,  
                "personId": item.personId,  
                "positionId": "ActivityDesign", 
                "id": item.id,
                "persistStatus": "fdel"  
            });
        })
       
        actions.ActivityDesign.saveBill({param,callback:(res)=>{
            if(res) {
                
                selectedList.map(selectItem=>{
                    shareList.map((item,i)=> {
                        if(item.id == selectItem.id) {
                            shareList.splice(i,1);
                            i--;
                        }
                    })
                })
                this.setState({shareList})
            }
        }})
    }

    openRef = () => {
        this.setState({showModal:true})
    }

    savePerson = (data) => {
        let param=[];
        let self = this;
        let {selectData} = this.props;
        let {shareList} = this.state;
        
        data.map(item=> {
            if(item.userid) {
                param.push({
                    "billId": selectData[0].id,  
                    "personId": item.userid,  
                    "positionId": "ActivityDesign",  
                    "persistStatus": "new"  
                });
            }else {
                Message.create({ content: '选中数据存在企业人员未生成用户,未生成企业人员的用户不会添加到共享人员列表', color: 'warning',duration: 15 });
            }
            
            
        })
        if(param.length == 0) return;

        actions.ActivityDesign.saveBill({param,callback:(res)=>{
            res.map(item=> {
                shareList.push({
                    creator:item.creator,
                    creationTime:selectData[0].creationTime,
                    personName:item.personName,
                    personId:item.personId,
                    id:item.id,
                    personCode:item.personCode,
                })
            })
            self.props.form.setFieldsValue({"person":null})
            self.setState({shareList});
        }})
    }


    render() {
        let {form,onCallback,showCreateCustomerModal} = this.props;
        let { shareList } = this.state;
        let column = [
            {
                title: "创建人",
                dataIndex: "creator",
                width: 110,
                key: "creator",
            },
            {
                title: "创建时间",
                dataIndex: "creationTime",
                width: 110,
                key: "creationTime",
                render:(text)=>{
                    return text && ts2Formatter(text);
                }
            },
            {
                title: "共享人",
                dataIndex: "personName",
                width: 110,
                key: "personName",
            },
        ];
        let self = this;
        let personData = JSON.parse(localStorage.getItem("loginUserInfo")||"{}");
        let {organization=[]} = personData;
        organization = organization[0] || {};
        return (
            <div>
                
                <Modal
                show={showCreateCustomerModal}
                autoFocus={false}
                enforceFocus={false}
                onHide={this.props.closeCreateModal} >
                <Modal.Header>
                    <Modal.Title>共享信息</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                <div className="button-group">
                    <Button onClick={this.delPerson}>删除人员</Button>
                    <span className="wrapper">
                        
                        <RefComponent
                                showModal={this.state.showModal}
                                multiple={true}
                                key={`person`}
                                title={"人员"}
                                refName={"terminalPersonRef"}
                                childType={"DataHeader"}
                                clearMatchData={this.clearMatch}
                                clientParam={`{"EQ_isEnable":"1","EQ_dr":"0","EQ_personPosts.organization.id":"`+organization.organizationId+`"}`}
                                fieldName={"person"}
                                refTableOnClickSave={(refName, fieldName, data) => {
                                    self.savePerson(data);
                                }}
                                form={this.props.form}
                            />
                        <Button onClick={this.openRef}>增加人员</Button>
                    </span>
                    
                </div>
                    <MultiSelectTable 
                        columns={column} 
                        data={shareList || []}
                        scroll={{ y: 450 }}
                        getSelectedDataFunc={this.getSelectedDataFunc}
                    >
                    </MultiSelectTable>
                </Modal.Body>

                <Modal.Footer>
                    <Button onClick={()=>{
                        this.setState({shareList:null},()=>{
                            this.props.closeCreateModal();
                        })
                    }} style={{ marginRight: 10 }}><FormattedMessage id="js.Ref.Ref224.0012" defaultMessage="关闭" /></Button>
                </Modal.Footer>
            </Modal>
        </div>
        )
    }
}

export default FormList.createForm()(injectIntl(CreateCustomer))
